<template>
  <div>
    <h4>背景</h4>
    <div>
      字段联动，在日常开发中也是比较场景的，
      某个字段的状态可以驱动其他字段是否需要
      <span class="red">校验</span>，以及<span class="red">显示隐藏</span>等
    </div>

    <el-form inline :model="formModel" :rules="rules" ref="form">
      <el-form-item label="地址" prop="address">
        <el-input v-model="formModel.address"></el-input>
      </el-form-item>
      <el-form-item label="是否有营业执照" prop="hasLicense">
        <el-select v-model="formModel.hasLicense">
          <el-option label="有" value="1"></el-option>
          <el-option label="无" value="0"></el-option>
        </el-select>
      </el-form-item>

      <!-- v-show 的形式 开发者手动维护 校验 -->
      <div v-show="formModel.hasLicense === '0'">
        <el-form-item label="原因" prop="reason">
          <el-input v-model="formModel.reason"></el-input>
        </el-form-item>
        <el-form-item label="预计申请时间" prop="time">
          <el-input v-model="formModel.time"></el-input>
        </el-form-item>
      </div>

      <!-- 直接使用 v-if  -->
      <div v-if="formModel.hasLicense === '1'">
        <el-form-item label="员工数" prop="employees">
          <el-input v-model="formModel.employees"></el-input>
        </el-form-item>
      </div>

      <div>
        <el-button type="primary" @click="submit">提交</el-button>
        校验结果 -- {{ valid }}
      </div>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'dynamic-field-check',
  data () {

    return {
      rules: {
        reason: [
          { required: true, validator: this.checkContent('reason', '原因不能为空'), trigger: ['change', 'blur'] }
        ],
        time: [
          { required: true, validator: this.checkContent('time', '预计申请时间不能为空'), trigger: ['change', 'blur'] }
        ],

        employees: [
          { required: true, message: '员工数不能为空', trigger: ['change', 'blur'] }
        ]
      },
      formModel: {
        address: '',
        hasLicense: '',
        reason: '',
        employees: '',
        time: ''
      },
      valid: false
    }
  },
  watch: {
    'formModel.hasLicense' (val) {
      if (val === '0') {
        // 清空脏数据
        this.formModel.reason = ''
        this.formModel.time = ''
        // 清空 红色提示
        this.$refs['form'].clearValidate(['reason', 'time'])
      } else {
        this.formModel.employees = ''
      }
    }
  },
  methods: {
    checkContent (key, msg) {
      return (rule, value, callback) => {
        if (this.formModel.hasLicense !== '1') {
          if (!value) return callback(msg)
        }

        callback()
      }
    },
    submit () {
      this.$refs['form'].validate(((valid) => {

        this.valid = valid
        if(valid) console.log('校验通过')
      }))
    }
  }
}
</script>

<style lang="less" scoped>
.red {
  color: red;
  font-weight: 700;
}
</style>
